<template>
  <BasicDrawer
    class="basic-drawer-role"
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
    @close="close"
  >
    <BasicForm @register="registerForm">
    </BasicForm>
    <div class="tree-content-role relative">
      <div class="title mb-10px">菜单分配</div>
      <a-tree
        v-if="treeData.length > 0"
        ref="treeRef"
        v-model:checkedKeys="checkedKeys"
        :defaultExpandAll="true"
        checkable
        :tree-data="treeData"
        :fieldNames="{children:'children', title:'pathName', key:'id' }"
      >
      </a-tree>
    </div>
  </BasicDrawer>
</template>

<script lang="ts" setup>
import { ref, computed, unref, watch } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { formSchema } from './role.data';
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { selectMenuList,saveOrUpdateRole } from '@/api/role/index.ts'
import { message } from 'ant-design-vue'

const treeRef = ref()
const checkedKeys = ref([])
const treeData = ref([])
const emit = defineEmits(['success', 'register']);
const isUpdate = ref(true);
const editId = ref()
const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 90,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
});

const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    isUpdate.value = !!data?.isUpdate;
    resetFields();
    setDrawerProps({ confirmLoading: false });
    if (unref(treeData).length === 0) {
        let params = {}
        if(data?.record?.id){
          params = { roleId: data.record.id }
        }
        const res = await selectMenuList(params)
        if(res.code == 10000){
        treeData.value = res.data || []
        if(res.data.length){
            let list = []
            res.data.forEach(item => {
              list = [...list, ...item.checkedChildrenIds] as any
            })
            checkedKeys.value = list
        }
        }
    }
    if (unref(isUpdate)) {
        editId.value = data.record.id
        setFieldsValue({
          ...data.record,
        })
    }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增角色' : '编辑角色'))

// 提交表单
async function handleSubmit() {
    const { checkedKeys,halfCheckedKeys } = treeRef.value
    try {
        const values = await validate();  
        setDrawerProps({ confirmLoading: true })
        let params = {
          ...values,
          menuIds: checkedKeys.concat(halfCheckedKeys),
          checkedChildrenIds: checkedKeys
        }
        if(unref(isUpdate)){
          params.id = editId.value
        }
        const res = await saveOrUpdateRole(params)
        if(res.code == 10000){
          message.success('保存成功')
          close()
          emit('success')
        }else{
          message.error(res.msg)
        }
    } finally {
        setDrawerProps({ confirmLoading: false })
    }
}

function close(){
    closeDrawer()
    treeData.value = []
}
</script>

<style lang="less" scoped>
.tree-content-role{
  margin-top: 10px;
  .title{
    font-size: 16px;
    font-weight: bold;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
    width: 110%;
    padding-bottom: 10px;
    top: 0;
    left: -16px;
    padding-left: 10px;
  }
}
</style>

<style>
.ant-drawer .ft-basic-title{
  font-weight: bold;
}
</style>
